package com.enation.app.javashop.core.trade.order.service.impl;

import com.enation.app.javashop.core.base.CachePrefix;
import com.enation.app.javashop.core.trade.order.service.TradeSnCreator;
import com.enation.app.javashop.framework.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;

/**
 * 交易，订单编号创建
 * @author Snow create in 2018/4/9
 * @version v2.0
 * @since v7.0.0
 */
@Service
public class TradeSnCreatorImpl implements TradeSnCreator {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public String generateTradeSn() {
        String key = CachePrefix.TRADE_SN_CACHE_PREFIX.getPrefix();
        String sn = generateSn(key);
        return sn;
    }

    @Override
    public String generateOrderSn() {
        String key = CachePrefix.ORDER_SN_CACHE_PREFIX.getPrefix();
        String sn = generateSn(key);
        return sn;
    }

    @Override
    public String generatePayLogSn() {
        String key = CachePrefix.PAY_LOG_SN_CACHE_PREFIX.getPrefix();
        String sn = generateSn(key);
        return sn;
    }

    @Override
    public void cleanCache() {
        Date yesterday = getYesterday();
        String timeStr = DateUtil.toString(yesterday,"yyyyMMdd");
        stringRedisTemplate.delete(CachePrefix.TRADE_SN_CACHE_PREFIX.getPrefix()+"_"+timeStr);
        stringRedisTemplate.delete(CachePrefix.ORDER_SN_CACHE_PREFIX.getPrefix()+"_"+timeStr);
    }


    private  Date getYesterday(){
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        return  cal.getTime();
    }


    /**
     * 通过Redis的自增来控制编号的自增
     * @param key 区分类型的主key，日期会连在这个key后面
     * @return 生成的编码
     */
    private  String generateSn(String key){

        String timeStr = DateUtil.toString(new Date(),"yyyyMMdd");
        //组合出当天的Key
        String redisKey = key+"_"+timeStr;

        //用当天的时间进行自增
        Long snCount=stringRedisTemplate.opsForValue().increment(redisKey, 1);
        String sn ;

        //预计每天订单不超过1百万单
        int num = 1000000;
        if( snCount < num){
            sn  = "000000" + snCount;
            sn = sn.substring(sn.length()-6,sn.length());
        }else{
            sn = String.valueOf(snCount);
        }
        sn=timeStr+sn;
        return sn;
    }

}
